<?php
/**
 * Created by PhpStorm.
 * User: songs
 * Date: 2020/5/16
 * Time: 16:04
 */

namespace App\admin\FormView;


use App\Jobs\Fun;

abstract class BaseViewForm
{
    /**
     * 返回对象模型
     */
    abstract public function get_model();

    /**
     * 需要继承,然后定义每行需要显示的数据格式
     */
    abstract public function Labels();
    /**
     * return [
     * [
     * 'title'=>'这是标题',
     * 'field'=>'name',
     * 'type'=>self::labelType,
     * 'must'=>true,
     * 'attr'=>['test'=>'123']
     * ],
     * [
     * 'title'=>'这是图片',
     * 'field'=>'head',
     * 'type'=>self::labelPic,
     * 'must'=>true,
     * 'attr'=>['test'=>'123']
     * ],
     * [
     * 'title'=>'多行文本',
     * 'field'=>'notes',
     * 'type'=>self::labeltextarea,
     * 'must'=>true,
     * 'attr'=>['test'=>'123']
     * ],
     * [
     * 'title'=>'富文本',
     * 'field'=>'notesHtml',
     * 'type'=>self::labeltexthtml,
     * 'must'=>true,
     * 'attr'=>['test'=>'123']
     * ],
     * [
     * 'title'=>'性别',
     * 'field'=>'sex',
     * 'type'=>self::labelType,
     * 'must'=>true,
     * 'attr'=>['test'=>'123'],
     * 'list'=>[
     * ///1男，2女，
     * 0=>'未知',
     * 1=>'男',
     * 2=>'女'
     * ]
     * ],
     * [
     * 'title'=>'复选框',
     * 'field'=>'testfield',
     * 'type'=>self::labelcheckbox,
     * 'must'=>true,
     * 'attr'=>['test'=>'123'],
     * 'list'=>[
     * 1=>'测试数据1',
     * 2=>'测试数据2',
     * 3=>'测试数据3',
     * 4=>'测试数据4',
     * ]
     * ],
     * ];
     */

    /**
     * 表单提交地址
     */
    public $action = '';
    /**
     * 表单提交按钮显示的文本,如果为空,则不现实按钮
     */
    public $submit = '保存';
    /**
     * 是否为只读模式
    */
    protected $readOnly=false;

    /**
     * 主键的字段
     */
    public function get_primaryKey()
    {
        $pr = $this->get_model();
        $key = $pr->getKeyName();
        if (isset($key)) {
            return $key;
        } else {
            Fun::showmsg('获取primaryKey错误', Fun::ERROR_SHOW);
        }
    }


    private $_oneMdel = false;

    /**
     * 获取表单数据
     */
    public function getOneModel()
    {

        if ($this->_oneMdel !== false) {
            return $this->_oneMdel;
        }
        $key = $this->get_primaryKey();
        $one = $this->get_model()->where([
            $key => $_GET[$key]
        ])->first();
        $this->_oneMdel = $one;
        return $one;
    }

    /**
     * 更新表单数据
     */
    public function setOneModel()
    {

    }

    /**
     * 删除表单数据
     */
    public function deleteOneModel()
    {

    }


    /**
     * 这是文本展示
     */
    const labeltextshow = 'textshow';
    /**
     * 普通文本类型
     */
    const labelTypeTextEdit = 'Edit';
    /**
     * 图片类型
     */
    const labelPic = 'pic';
    /**
     * textarea类型
     */
    const labeltextarea = 'textarea';
    /**
     * 富文本类型
     */
    const labeltexthtml = 'texthtml';
    /**
     * 下拉列表类型
     */
    const labelDownList = 'DownList';
    /**
     * 复选框
     */
    const labelcheckbox = 'checkbox';


    public $Request = null;///Request $request


    public function __construct($Request = null)
    {
        $this->Request = $Request;
    }


    public $breadcrumb = '<li><a href="/admin">Home</a></li>
        <li><a href="javascript:;">系统</a></li>
        <li class="active">默认</li>';
    public $topTitle = '标题';


    public function get_html()
    {
        $one = $this->getOneModel();
        $ispost = false;
        $save = false;
        if (isset($_POST['_token'])) {
            // print_r($_POST);exit;
            $ispost = true;
            $save=$this->saveModel($one,$_POST);
            if (!$save) {
                Fun::showmsg("保存失败");
            }
        }
        return $this->render("form", [
            'one' => $one,
            'ispost' => $ispost,
            'save' => $save
        ]);
    }

    protected function saveModel(&$one, $POST)
    {
        if (!$one) {
            $one = $this->get_model();
        }
        foreach ($this->Labels() as $vo) {
            if (isset($vo['save']) && $vo['save']) {
                $one[$vo['field']] = $POST[$vo['field']];
                if($vo['type']==self::labelcheckbox){
                  $one[$vo['field']]= implode(',',$one[$vo['field']]);
                }
            }
        }
      //  print_r($one);exit;
        return $one->save();
    }

    public function getName()
    {
        return md5(self::className());
    }

    /**
     * Returns the fully qualified name of this class.
     * @return string the fully qualified name of this class.
     * @deprecated since 2.0.14. On PHP >=5.5, use `::class` instead.
     */
    public static function className()
    {
        return get_called_class();
    }

    public function render($view, $params = [])
    {

        $context = $this;
        $model = null;
        $topselect = null;
        if (isset($params['model'])) {
            $model = $params['model'];
        }
        if (isset($params['topselect'])) {
            $topselect = $params['topselect'];
        }

        /*
        $html = view('baseviewlist.' . $view,
            compact('context', 'model', 'topselect'))->render();
        */
        $params['context'] = $context;
        $params['model'] = $model;
        $params['topselect'] = $topselect;
        $html = view('baseviewlist.' . $view,
            $params)->render();
        return $html;
        // return parent::render('@app/components/baseviewlist/' . $view, $params);
    }

    /**
     * 方便继承,多一层过滤
     */
    public function ModelTohtml($key, $model)
    {
        return $model->$key;
    }

    /**
     * 属性数组转换成字符串
     */
    private function arrayArrayToStr($attrArray)
    {
        $attr = '';
        foreach ($attrArray as $k => $v) {
            $attr .= ' ' . $k . '="' . $v . '"';
        }
        return $attr;
    }

    /**
     * 生成表单的各个标签
     */
    public function renderTag($vo)
    {
        $html = '<div class="am-form-group clearfix">';
        $model = $this->getOneModel();
        if ($model) {
            $value = $this->ModelTohtml($vo['field'], $model);
        } else {
            $value = null;
        }
        $html .= '<lable class="label">' . $vo['title'] . '</lable>';
        $input = $value;

        if($vo['type']==self::labeltextshow){
            $input = '<div class="labelvalueDiv labeltextshow">'.$value."</div>";
        }

        if($vo['type']==self::labelTypeTextEdit){
            $input = '<div class="labelvalueDiv">
                        <input '.($this->readOnly?"readonly":"").' class="" type="text" ' . $this->arrayArrayToStr($vo['attr']) .
            '  name="' . $vo['field'] . '" value="' . $value . '"  ></div>';
        }

        if ($vo['type'] == self::labelPic) {
            $input = '<div '.($this->readOnly?"readonly":"").' 
             class="labelvalueDiv">'.$this->renLabelPic($vo, $value, $model).'</div>';
        }
        if ($vo['type'] == self::labeltextarea) {
            $input = '<div  class="labelvalueDiv">'.$this->renLabeltextarea($vo, $value, $model).'</div>';
        }

        if ($vo['type'] == self::labeltexthtml) {
            $input = '<div  class="labelvalueDiv">'.$this->renLabeltexthtml($vo, $value, $model).'</div>';
        }
        if ($vo['type'] == self::labelDownList) {
            $input = '<div class="labelvalueDiv">'.$this->renLabelDownList($vo, $value, $model).'</div>';
        }
        if ($vo['type'] == self::labelcheckbox) {
            $input = '<div  class="labelvalueDiv">'.$this->renLabelcheckbox($vo, $value, $model).'</div>';
        }

        $html .= $input;
        $html .= '</div>';
        return $html;
    }

    /**
     * 生成图片类型
     */
    protected function renLabelPic($vo, $value, $model)
    {

        $html = '<div class="renLabelPic" ' . $this->arrayArrayToStr($vo['attr']??[]) . ' >
                <img src="' . Fun::pImg($value) . '" field="' . $vo['field'] . '" class="pic"/>
               <input type="hidden" name="' . $vo['field'] . '" value="' . $value . '"/>
               <input type="file" fileimg="' . $vo['field'] . '" title="选择文件上传"/> 
        </div>';
        return $html;
    }

    /**
     * 生成图片类型
     */
    protected function renLabeltextarea($vo, $value, $model)
    {

        $html = '<div class="renLabeltextarea">
                <textarea '.($this->readOnly?"readonly":"").'  class="textarea" ' . $this->arrayArrayToStr($vo['attr']) . ' name="' . $vo['field'] . '">' . $value . '</textarea>
                
        </div>';
        return $html;
    }

    /**
     * 生成图片类型
     */
    protected function renLabeltexthtml($vo, $value, $model)
    {
        $html = '<div class="renLabeltextarea">
                <textarea '.($this->readOnly?"readonly":"").'  class="textarea kindeditor" ' . $this->arrayArrayToStr($vo['attr']) . ' name="' . $vo['field'] . '">' . $value . '</textarea> 
        </div>';
        return $html;
    }

    /**
     * 下拉框
     */
    protected function renLabelDownList($vo, $value, $model)
    {
        // print_r($vo);exit;
        $html = '<select name="' . $vo['field'] . '" class="">';
        foreach ($vo['list'] as $k => $v) {
            if ($k == $value) {
                $html .= '<option value="' . $k . '" selected="">' . $v . '</option>';
            } else {
                $html .= '<option value="' . $k . '">' . $v . '</option>';
            }
        }
        $html .= '</select>';
        return $html;
    }

    /**
     * 复选框
     */
    protected function renLabelcheckbox($vo, $value, $model)
    {
        //print_r($vo);exit;
        $valuearray = explode(",", $value);

        $html = '<div class="renLabelcheckbox">';
        foreach ($vo['list'] as $k => $v) {
            if (in_array($k, $valuearray)) {
                $html .= '<label '.($this->readOnly?"readonly":"").' class="checkboxlabel"><input type="checkbox" name="' . $vo['field'] . '[]"  value="' . $k . '"
                 checked="checked" /><span>' . $v . '</span></label>';
            } else {
                $html .= '<label '.($this->readOnly?"readonly":"").' class="checkboxlabel"><input type="checkbox" name="' . $vo['field'] . '[]"  value="' . $k . '"
                  /><span>' . $v . '</span></label>';
            }
        }
        $html .= '</div>';
        return $html;
    }


}